var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
import dictionary from '../../../utils/dictionary.js';
dictionary.multiArray = [dictionary.learnWayCopyList[0],dictionary.learnWayCopyList[1]]
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, {
  /**
   * 页面的初始数据
   */
  data: {
    ...dictionary,
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    memberInfo: {},
    customInfo: {source:'haha'},
    isLoading:false,
    multiIndex:[],
    scrollHeight:app.globalData.navHeight
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    let ctx = this;
    wx.showLoading({
    	title: "加载中"
    });
    ctx.setData({
      eOpenId: options.eOpenId,
      openId: options.openId,
    })
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
    });
    ctx.getMemberInfo();
    ctx.getCustomerInfo();
  },
  selectChange(e){
    let key = e.currentTarget.dataset.key
    console.log(key)
    this.setData({
      [`customInfo.${key}`]:this.data[key+'List'][e.detail.value]
    })
  },
  learnWayChange(e){
    let learnWay = this.data.multiArray[0].filter((item,index)=>e.detail.value[0]==index)[0];
    let learnWayDetail = this.data.multiArray[1][e.detail.value[1]]
    this.setData({
      multiIndex:e.detail.value,
      'customInfo.learnWay':learnWay,
      'customInfo.learnWayDetail':learnWayDetail
    })
  },
  learnWayParentChange(e){
    let that = this
    console.log('picker发送选择改变，携带值为', e)
    if(e.detail.column==0){
      console.log(e.detail.value+1)
      console.log(that.data.learnWayCopyList[e.detail.value+1])
      that.setData({
        'multiArray[1]':that.data.learnWayCopyList[e.detail.value+1]
      })
    }
  },
  namePropInput(e){
	  this.data.customInfo.name = e.detail.value;
  },
  positionPropInput(e){
	  this.data.customInfo.position = e.detail.value;
  },
  companyPropInput(e){
	  this.data.customInfo.company = e.detail.value;
  },
  telPropInput(e){
	  this.data.customInfo.tel = e.detail.value;
  },
  emailPropInput(e){
	  this.data.customInfo.email = e.detail.value;
  },
  addressPropInput(e){
	  this.data.customInfo.address = e.detail.value;
  },
  sourceForPropInput(e){
    this.data.customInfo.sourceFor = e.detail.value;
  },
  remarkPropInput(e){
	  this.setData({
    	 'customInfo.remark': e.detail.value
      });
  },
  sexChange(e) {
	  this.data.customInfo.sex = e.detail.value;
  },
  birthChange: function(e) {
      this.setData({
    	 'customInfo.birthday': e.detail.value
      });
  },
  getMemberInfo(){
	let ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/findRelation",
      data: {
        cusmallToken: cusmallToken,
        mOpenId: ctx.data.openId,
        eOpenId: ctx.data.eOpenId,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        let data = res.data;
        if (data && 0 === data.ret) {
          if(data.model.member){
            ctx.setData({
              memberInfo: data.model.member,
            });
          }
        }
      }
    });
  },
  showArea(){
    this.setData({
      showRemark:false,
      //navTop:0
      scrollHeight:app.globalData.navHeight
    })
  },
  hideArea(){
    this.setData({
      showRemark:true
    })
  },
  getCustomerInfo() {
	  let ctx = this;
	  wx.request({
		  url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/findMemberExinfo",
		  data: {
			 cusmallToken: cusmallToken,
			 openid: ctx.data.openId
		  },
		  header: {
			 'content-type': 'application/json'
		  },
		  success: function (res) {
			  let data = res.data;
			  if (0 == data.ret) {
				  ctx.setData({
					  customInfo: data.model.record || {}
          });
          let record = data.model.record
          if(res.data&&record&&record.learnWay&&record.learnWayDetail){
            let learnWayCopyList = JSON.parse(JSON.stringify(ctx.data.learnWayCopyList))
            let detailList = learnWayCopyList.splice(1),multiIndex=[]
            learnWayCopyList[0].map((item,index)=>{
              if(record.learnWay==item){
                multiIndex[0]=index
              }
            })
          
            if(multiIndex[0]||multiIndex[0]==0){
              detailList[multiIndex[0]].map((item,index)=>{
                if(item == record.learnWayDetail){
                  multiIndex[1] = index
                  ctx.setData({
                    multiIndex
                  })
                }
              })
            } else {
              ctx.setData({
                multiIndex:[]
              })
            }
          }
				  if (!ctx.data.customInfo.sex) {
					  ctx.data.customInfo.sex = ctx.data.memberInfo.sex == undefined ? 0 : ctx.data.memberInfo.sex;
				  }
				  wx.hideLoading();
			  } else {
				  wx.showModal({
					  title: data.msg,
					  icon: "none",
					  duration: 1000
				  });
			  }
		  }
	  })
  },
  extInfoCommit(e){
    let ctx = this;
    if (ctx.data.isLoading){
      wx.showToast({
         title: '不要重复提交',
         icon: "none"
      });
      return;
    }
    ctx.setData({
      isLoading:true
    });
    wx.showLoading({
      title: '提交中'
    });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/updateMemberExinfo",
      data: {
         cusmallToken: cusmallToken,
         openid: ctx.data.openId,
         name: ctx.data.customInfo.name || "",
     	   company: ctx.data.customInfo.company || "",
     	   position: ctx.data.customInfo.position || "",
     	   authTel: ctx.data.customInfo.authTel || "",
     	   tel: ctx.data.customInfo.tel || "",
     	   sex: ctx.data.customInfo.sex || 0,
     	   email: ctx.data.customInfo.email || "",
     	   address: ctx.data.customInfo.address || "",
     	   birthday: ctx.data.customInfo.birthday || "",
          remark: ctx.data.customInfo.remark || "",
          authTel:ctx.data.customInfo.authTel || "",
          sourceFor:ctx.data.customInfo.sourceFor || "",
          learnWay :ctx.data.customInfo.learnWay || '',
          learnWayDetail:ctx.data.customInfo.learnWayDetail || '',
          intentGrage:ctx.data.customInfo.intentGrage || '',
          putThrough:ctx.data.customInfo.putThrough || '',
          useHouse:ctx.data.customInfo.useHouse || '',
          intentProduct:ctx.data.customInfo.intentProduct || '',
          intentPrice:ctx.data.customInfo.intentPrice || '',
          intentHouseType:ctx.data.customInfo.intentHouseType || '',
          intentArea:ctx.data.customInfo.intentArea || '',
      },
      header: {
         'content-type': 'application/json'
      },
      success: function (res) {
        let data = res.data;
        wx.hideLoading();
        if (data && 0 === data.ret) {
          wx.showToast({
            title: '修改成功',
            icon: "none",
            success() {
              setTimeout(function(){
            	 let pages = getCurrentPages();//当前页面
                 let prevPage = pages[pages.length - 2];//上一页面
                 prevPage.setData({//直接给上移页面赋值
                    customInfo: ctx.data.customInfo
                 });
                 wx.navigateBack({
                    delta: 1
                 });
              },1000);
            }
          });
        }else{
          wx.showModal({
            title: data.msg,
            icon: "none",
            duration: 1000
          });
        }
      },
      fail() {
        wx.hideLoading();
      },
      complete() {
        ctx.setData({
          isLoading: false
        });
      }
    });
  },
  changeHeight(e){
    this.setData({
      //navTop:e.detail.height-(170/750*wx.getSystemInfoSync().windowWidth)-app.globalData.navHeight
      scrollHeight:e.detail.height+app.globalData.navHeight,
      scrollId:'textarea'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      scrollId:'textarea'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))